package com.ioc;

import lombok.extern.log4j.Log4j2;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author _G5niusX
 * @Date 2018/4/17 20:52
 */
@Log4j2
public class DefaultIOC implements IOC {

    private static final Map<String, BeanDefine> MAP = new ConcurrentHashMap<>(32);


    @Override
    public void addBean(Object object) {
        addBean(object.getClass().getName(), object);
    }

    @Override
    public void addBean(String name, Object object) {
        BeanDefine beanDefine = new BeanDefine(object);
        addBean(name, beanDefine);
        Class<?>[] interfaces = beanDefine.getBeanType().getInterfaces();
        if (interfaces.length > 0) {
            for (Class<?> c : interfaces) {
                this.addBean(c.getName(), beanDefine);
            }
        }
    }

    @Override
    public void addBean(String name, BeanDefine beanDefine) {
        if (MAP.put(name, beanDefine) != null) {
            System.out.println("bean已经被初始化过: " + name);
        }

    }

    @Override
    public Object getBean(String name) {
        BeanDefine beanDefine = MAP.get(name);
        if (beanDefine == null) {
            return null;
        }
        return beanDefine.getBean();
    }

    @Override
    public <T> T getBean(Class<T> tClass) {
        String name = tClass.getName();
        Object bean = getBean(name);
        return tClass.cast(bean);
    }
}
